from django.shortcuts import render
from django.views import View
from django import http
from django_redis import get_redis_connection

import json, pickle, base64

from goods.models import SKU
from meiduo_mall.utils.response_code import RETCODE



"""购物车"""
class CartsView(View):

    """购物车新增数据"""
    def post(self, request):

        #获取请求体中的sku_id, count
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        #校验
        if all([sku_id, count]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('sku不存在')

        #判断当前用户是否登陆
        user = request.user
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})

        if user.is_authenticated:

            #如果登陆，储存购物车数据到redis
            #创建redis连接对象
            redis_conn = get_redis_connection("carts")
            pl = redis_conn.pipeline()

            """
                hash: {sku_id_1: count, sku_id_2: count2}
                set: {sku_id_1, sku_id_2}
            
            """

            #hincrby()
            pl.hincrby('carts_%s' % user.id, sku_id, count)

            #sadd()
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)

            pl.execute()

        else:

            #如果未登录，储存购物车数据到cookie
            """
            {
                sku_id_1:{'count':2, 'selected':Ture},
                sku_id_2:{'count':3, 'selected':Ture},
                
            }
            
            将carts字典转换成cart_str
            a = pickle.dumps(cart_dict)    # b'x01x23'
            a = base64.b64encode(a)        # b'kjnfgksanks'
            a.decode()                     # kjnfgksanks
            
            将cart_str字符串转换成cart_dict
            A = cart_str.encode()          # b'kjnfgksanks'
            A = base64.b64decode(A)        # b'x01x23'
            cart_dict = pickle.loads(A)    # {''}
            
            """
            #先获取cookie购物车数据
            cart_str = request.COOKIES.get('carts')
            #如果cookie中已有购物车数据
            if cart_str:
                #把cookie购物车字符串转回到字典
                cart_str_bytes = cart_str.encode()
                cart_bytes = base64.b64decode(cart_str_bytes)
                cart_dict = pickle.loads(cart_bytes)

            else:
            #如果cookie中没有购物车数据
                #准备一个空字典
                cart_dict = {}

            #判断要添加的sku_id在字典中是否存在，如果存在，需要多count做增量计算
            if sku_id in cart_dict:
                origin_count = cart_dict[sku_id]['count']
                count += origin_count

            #添加
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            #把购物车字典转回字符串，然后重新设置到cookie中
            cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 响应
            response.set_cookie('carts', cart_str)
        return response

    """购物车的数据展示"""
    def get(self, request):

        user = request.user
        if user.is_authenticated:
            """登陆用户获取redis购物车数据
                hash: {sku_id_1: count, sku_id_2}
                set: {sku_id_1, sku_id_2}
            """
            #创建redis连接对象
            redis_conn = get_redis_connection('carts')

            #获取hash数据
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)

            #获取set数据
            selected_ids = redis_conn.smembers('selected_%s' % user.id)

            #将redis购物车数据格式转换成和cookie购物车数据格式一致，目的是为了数据查询转换代码和cookie共用一套代码
            cart_dict = {}
            for sku_id_bytes, count_bytes in redis_cart.items():
                cart_dict[int(sku_id_bytes)] = {
                    "count": int(count_bytes),
                    'selected': sku_id_bytes in selected_ids
                }


        else:
            """未登录用户获取cookie购物车数据
                {
                    sku_id_1:{'count':2, 'selected':Ture},
                    sku_id_2:{'count':3, 'selected':Ture},
                }
            """
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                return render(request, 'cart.html')

        sku_qs = SKU.objects.filter(id__in=cart_dict.keys())
        cart_skus = []
        for sku in sku_qs:
            sku_dict = {
                'id': sku.id,
                'name': sku.name,
                'price': str(sku.price),
                'default_image_url': sku.default_image.url,
                'count': int(cart_dict[sku.id]['count']),
                'selected': str(cart_dict[sku.id]['selected']),
                'amount': str(sku.price * int(cart_dict[sku.id]['count']))
            }

            cart_skus.append(sku_dict)

        context = {
            'cart_skus': cart_skus
        }

        return render(request, 'cart.html', context)
        pass

    """购物车的数据修改"""
    def put(self,request):

        #接收前端传入 sku_id, count, selected
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected')

        if all ([sku_id, count]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('sku不存在')

        user = request.user

        # 响应给前端修改后的sku数据
        cart_sku = {
            'id': sku.id,
            'name': sku.name,
            'price': sku.price,
            'default_image_url': sku.default_image.url,
            'count': int(count),
            'selected': selected,
            'amount': sku.price * int(count),
        }

        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车数据成功', 'cart_sku': cart_sku})

        #判断用户是否登陆
        if user.is_authenticated:  #如果登陆，就是修改redis购物车数据

            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            pl.hset('carts_%s' % user.id, sku_id, count) #覆盖hash中的数据

            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)  # 将勾选的sku_id存储到set集合
            else:
                pl.srem('selected_%s' % user.id, sku_id)  # 不勾选时,将sku_id从set集合中移除

            pl.execute()


            pass

        else:  #如果没有登陆，就是修改cookie购物车数据

            cart_str = request.COOKIES.get('carts')

            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': 'cookie数据没有获取'})

            # 修改购物车大字典数据,新值覆盖旧值
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected,
            }

            # 将字典转换成字符串
            cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            response.set_cookie('carts', cart_str)

        return response

    """购物车的数据删除"""
    def delete(self, request):

        #接受sku_id
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('sku不存在')

        #判断是否登录
        user = request.user
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

        if user.is_authenticated:  # 如果登录操作redis数据

            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            pl.hdel('carts_%s' % user.id, sku_id)    # 删除hash中的sku_id及count
            pl.srem('selected_%s' % user.id, sku_id) # 删除set集合中的勾选

            pl.execute()

        else:                      # 如果未登录操作cookie数据

            cart_str = request.COOKIES.get('carts')

            # 判断cookie是否获取到
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': 'cookie没有获取到'})

            # 判断当前要删除的sku_id在字典中是否存在
            if sku_id in cart_dict:
                del cart_dict[sku_id]

            if len(cart_dict.keys()) == 0:       # 如果cookie中的购物车数据已经删除完了
                response.delete_cookie('carts')  # 删除cookie


            cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            response.set_cookie('carts', cart_str)

        return response


"""购物车全选功能"""
class CartsSelectAllView(View):

    def put(self, request):

        #接收数据
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected')

        if isinstance(selected, bool) is False:   #判断接收到的selected是否是bool类型
            return http.HttpResponseForbidden('参数有误')

        #判断用户是否登录
        user = request.user
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

        if user.is_authenticated:  # 用户已登录，操作redis购物车

            # 创建redis连接对象
            redis_conn = get_redis_connection('carts')
            # 获取到hash购物车数据{sku_id: count}
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)

            #判断当前是全选还是全不选
            if selected:
                redis_conn.sadd('selected_%s' % user.id, *redis_cart.keys())  #如果是全选把hash中的所有sku_id添加到set集合中
            else:
                redis_conn.delete('selected_%s' % user.id)  # 如果取消全选,把hash中的所有sku_id 从set集合中删除

        else:    # 用户未登录，操作cookie购物车

            cart_str = request.COOKIES.get('carts')  # 获取cookie购物车数据

            if cart_str:
                # 如果获取到把字符串转换成字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))

            else:
                # 如果没有获取到直接响应
                return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': 'cookie数据没有获取到'})

            """
                {
                    sku_id: {'count': 1, 'selected': True}
                }
            """
            # 遍历cookie购物车大字典,把里面的selected改为True或False
            for sku_id in cart_dict:
                cart_dict[sku_id]['selected'] = selected

            cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            response.set_cookie('carts', cart_str)

        return response


"""我的购物车,数据展示"""
class CartsSimpleView(View):

    def get(self, request):

        user = request.user
        if user.is_authenticated:   # 登录用户获取redis购物车数据
            """
                hash: {sku_id_1: count, sku_id2: count}
                set: {sku_id_1, sku_id_2}
            """
            redis_conn =get_redis_connection('carts')
            redis_cart = redis_conn.hgetall('carts_%s' % user.id) #获取hash数据

            selected_ids = redis_conn.smembers('selected_%s' % user.id)  #获取set数据{b'1', b'2'}        ???

            cart_dict = {}
            for sku_id_bytes, count_bytes in redis_cart.items():
                cart_dict[int(sku_id_bytes)] = {
                    'count': int(count_bytes),
                    'selected': sku_id_bytes in selected_ids
                }

        else:   # 未登录用户获取cookie购物车数据

            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '没有购物车数据'})

        """
          {
              sku_id_1: {'count': 2, 'selected': True},
              sku_id_2: {'count': 2, 'selected': True}
          }
        """
        # 查询到购物车中所有sku_id对应的sku模型
        sku_qs = SKU.objects.filter(id__in=cart_dict.keys())      #  ???
        cart_skus = []  # 用来装每个转换好的sku字典
        for sku in sku_qs:
            sku_dict = {
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url,
                'count': int(cart_dict[sku.id]['count']),
            }
            cart_skus.append(sku_dict)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'cart_skus': cart_skus})














